<template>
  <div class="ek-tag">
    <el-tag
      v-for="tag in dynamicTags"
      :key="tag"
      closable
      :disable-transitions="false"
      @close="handleClose(tag)"
      class="tag-margin"
    >
      {{ tag }}
    </el-tag>
    <el-input
     class="tag-input"
      v-if="inputVisible"
      ref="inputRef"
      v-model="inputValue"
      size="small"
      @keyup.enter="handleInputConfirm"
      @blur="handleInputConfirm"
    />
    <el-button v-else size="small" @click="showInput"> + New Tag </el-button>
  </div>
</template>

<script setup>
import { defineEmits, nextTick, onMounted, ref, computed } from "vue";
const props = defineProps({
  modelValue: {
    type: Array,
    default: () => [],
  },
});
const emit = defineEmits(['update:modelValue'])
const dynamicTags = computed({
  get() {
    return props.modelValue
  },
  set(value) {
    emit('update:modelValue', value)
  }
})

const inputValue = ref("");
const inputVisible = ref(false);
const inputRef = ref(null);

const handleClose = (tag) => {
   
    dynamicTags.value = dynamicTags.value.filter(item => item !== tag);
};

const showInput = () => {
  inputVisible.value = true;
  nextTick(() => {
    inputRef.value?.input.focus();
  });
};

const handleInputConfirm = () => {
  if (inputValue.value) {
    dynamicTags.value.push(inputValue.value);
  }
  inputVisible.value = false;
  inputValue.value = "";
};
onMounted(() => {
  dynamicTags.value = props.value;
});
</script>
<style lang="scss" scoped>
.ek-tag {
    text-align: left;
  .tag-margin {
    margin: 4px;
  }
  .tag-input {
    width: 100px;
  }
}
</style>
